package com.yxhl.zoume.core.main.presenter;

import android.content.Context;

import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.common.presenter.BasePresenter;
import com.yxhl.zoume.common.presenter.IPresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.core.main.ui.view.MainView;
import com.yxhl.zoume.data.http.rest.param.CheckUpdateParam;
import com.yxhl.zoume.data.http.rest.response.login.CheckUpdateResponse;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.domain.interactor.updateapp.CheckAppVersionUseCase;
import com.yxhl.zoume.utils.DiskCacheUtils;

import javax.inject.Inject;

/**
 * Created by sugarya on 16/5/11.
 */
public class CheckAppUpdatePresenter extends BasePresenter implements IPresenter {

    @Inject
    CheckAppVersionUseCase mCheckAppVersionUseCase;

    MainView mMainView;
    Context mContext;

    @Inject
    public CheckAppUpdatePresenter(Context context) {
        super(context);
        mContext = context;
    }

    public void checkAppUpdate() {
        if (ZouMeApplication.application.isFirstTimeCheckedAppUpdate) {
            CheckUpdateParam param = new CheckUpdateParam(
                    getMobile(),
                    getToken(),
                    getClientVersionName(),
                    DiskCacheUtils.getInstance(mContext).getDeviceToken()
            );
            mCheckAppVersionUseCase.execute(param,new ZMSubscriber<CheckUpdateResponse>() {
                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                            ZouMeApplication.application.isFirstTimeCheckedAppUpdate = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            ZouMeApplication.application.isFirstTimeCheckedAppUpdate = false;
                        }

                        @Override
                        public void onNext(CheckUpdateResponse checkUpdateResponse) {
                            super.onNext(checkUpdateResponse);
                            if (checkUpdateResponse != null) {
                                boolean succ = checkUpdateResponse.isSucc();
                                if (succ) {
                                    mMainView.renderUpdateAppVersionDataOnSuccess(checkUpdateResponse);
                                }
                            }
                        }
                    });
        }
    }


    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy() {
        mCheckAppVersionUseCase.unsubscribe();
    }

    @Override
    public void attachView(BaseView view) {
        if (view instanceof MainView) {
            mMainView = (MainView) view;
        }
    }
}
